
### -------------------------------------------------- 
### ---- General Set Up ---- 
### -------------------------------------------------- 

### Clear global environment
rm(list=ls()) 


### Libraries:
library(pacman)
pacman::p_load(tidyverse, here)


### File Location (R project only)
here::i_am("Survey and App Match/108_generate_state_subsets.R")
file_path <- here()
file_path_data_matched <- here("Survey and App Match/Temp_Data/")


### -------------------------------------------------- 
### Load Data: TFA Data
### -------------------------------------------------- 

### Load tfa_dat_flag from file #7
load(paste0(file_path_data_matched,"/tfa_to_state_ALL_flags_v2.RData")) #changed name 

### -------------------------------------------------- 
### Subset set up 
### -------------------------------------------------- 

### Variables to Save
varnames_all <- c("personid", "FirstName", "LastName", "Sex",
                  "BirthYear", #"BirthMonth", "BirthDay",
                  "LandLine_AreaCode", "LandLine_Number",
                  "CellPhone_AreaCode", "CellPhone_Number",
                  "Current_Address.Zip", "Permanent_Address.Zip")


### List of state abbreviations 
data(state) #Download list of state abbreviations
state_abb_w_DC <- c("DC",state.abb) #Add DC to list of state abbreviations


### -------------------------------------------------- 
### Save subsets 
### -------------------------------------------------- 

### Generate files with subset tagged for each state
for(s in 1:51){ #Run loop for all 50 states plus DC
  
  ABB <- state_abb_w_DC[s] #Assign variable with one of 51 abbreviations
  
  # Subset to selected state 
  tfa_dat_match_state <- tfa_dat_flag %>%
    filter_(paste0("state_",ABB,"_flag == 1")) %>%
    select(varnames_all, 
           c(paste0("state_ca_",ABB), paste0("state_uni_",ABB), paste0("state_st_",ABB), 
             paste0("state_mr_",ABB), paste0("state_cell_",ABB)))  
  
  save(tfa_dat_match_state, 
       file=paste0(file_path_data_matched,"/State_TFA_Subsets/tfa_to_state_",ABB,"_flags_v2.RData")) #changed name
}
